<template>
  <div class="edit">
    <div class="edit-title">
      <span class="title-1">学习中心</span> /
      <span class="title-1">我的专题培训</span> /
      <span class="title-2">{{ ziceTitle }}</span>
    </div>
    <div class="edit-content">
      <div class="edit-content-left">
        <div class="edit-content-left-title">{{ examInfo.fullName }}</div>
        <div class="edit-content-left-content" v-for="(item, index) in listData" :key="index"
          v-show="currentIndex === index">
          <div class="edit-content-left-content-item1">
            <div>{{ getQuestionTypeName(item.questionType) }}</div>
            <div>{{ currentIndex + 1 }}/{{ listData.length }}</div>
          </div>
          <div class="edit-content-left-content-item2">
            <div>{{ item.title }}</div>
            <template v-if="item.questionType != 'determine'">
              <div class="edit-content-left-content-item2-1">
                <div v-for="(option, i) in item.options" :key="i">
                  <p v-if="!option.img">{{ option.label }}.{{ option.content }}</p>
                  <div v-else>{{ option.label }}.<img :src="define.comUrl + option.img" /></div>
                </div>
              </div>
            </template>    
          </div>
          <template v-if="item.titleImgs">
            <div v-for="(cItem, cIndex) in JSON.parse(item.titleImgs)" :key="cIndex" style="display:inline-block; margin:0 10px;">
              <img :src="define.comUrl + cItem" style="max-width: 400px;" />
            </div>
          </template>
        </div>
      </div>
      <div class="edit-content-right">
        <div class="edit-content-right-title">
          <div>考试时间</div>
          <div>倒计时：{{ countdownTime }}</div>
        </div>
        <!-- 选择题 -->
        <div class="edit-content-right-content" v-if="currentQuestion.questionType == 'multiple'">
          <div class="edit-content-right-item">请选择</div>
          <div class="edit-content-right-item-1">
            <div class="edit-content-right-item-2" 
                v-for="(option, i) in currentQuestion.options" :key="i"
                :class="[{ 'active': Array.isArray(currentQuestion.answer) && currentQuestion.answer.includes(i) }]"
                @click="selectOption(currentQuestion, i, 'mul')">
              {{ option.label }}
            </div>
          </div>
        </div>
        <!-- 填空题 -->
        <div class="edit-content-right-content" v-if="currentQuestion.questionType == 'blank'">
          <div class="edit-content-right-item">请填空</div>
          <div>
            <el-form
              label-position="top"
              label-width="80px"
            >
              <el-form-item label="填空1">
                <el-input v-model="currentQuestion.answer"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 问答题 -->
        <div class="edit-content-right-content" v-if="currentQuestion.questionType == 'answers'">
          <div class="edit-content-right-item">请答题</div>
          <div>
            <el-form
              label-position="top"
              label-width="80px"
            >
              <el-form-item label="答">
                <el-input
                  type="textarea"
                  v-model="currentQuestion.answer"
                  :rows="8"
                  placeholder="请输入答案"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 判断 -->
        <div class="edit-content-right-content" v-if="currentQuestion.questionType == 'determine'">
          <div class="edit-content-right-item">请选择</div>
          <div class="edit-content-right-item-1">
            <div class="edit-content-right-item-2" v-for="(option, i) in ['√', '×']" :key="i"
              :class="[{ 'active': currentQuestion.answer === i }]" @click="selectOption(currentQuestion, i)">{{
              option }}</div>
          </div>
        </div>
        <div class="edit-content-right-btn">
          <el-button @click="prevQuestion" v-if="currentIndex > 0">上一题</el-button>
          <el-button @click="nextQuestion" v-if="currentIndex < listData.length - 1">下一题</el-button>
          <el-button @click="submitExam" v-if="currentIndex === listData.length - 1">提交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { startExamTask, submitExamTask } from "@/api/exam";

export default {
  data() {
    return {
      ziceTitle: '理论考试',
      id: this.$route.query.id,
      types: this.$route.query.type,
      examInfo: {},
      currentIndex: 0,
      countdownTime: '',
      timer: null,
      currentQuestion: {}
    };
  },
  computed: {
    listData() {
      if (this.examInfo.examTask && this.examInfo.examTask.temsexamtaskresultList && this.examInfo.examTask.temsexamtaskresultList.length > 0) {
        return this.examInfo.examTask.temsexamtaskresultList.map(v => {
          return {
            ...v,
            options: v.options ? JSON.parse(v.options) : []
          }
        });
      }
      return [];
    }
  },
  watch: {
    currentIndex: {
      immediate: true,
      handler(newVal) {
        this.currentQuestion = this.listData[newVal] || {};
      }
    },
    listData: {
      immediate: true,
      handler(newVal) {
        this.currentQuestion = newVal[this.currentIndex] || {};
      }
    }
  },
  created() {
    this.getExamTaskDetail();
    if (!this.id) {
      this.$message.error('请先选择考试');
      this.$router.go(-1);
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    startTimer() {
      // 设置考试时间为2小时
      let minutes = this.examInfo.examLength || 0;
      let seconds = 0;

      this.timer = setInterval(() => {
        if (seconds === 0) {
          minutes--;
          seconds = 59;
        } else {
          seconds--;
        }

        if (minutes === 0 && seconds === 0) {
          clearInterval(this.timer);
          this.$message.warning('考试时间已到！');
          this.submitExam();
        }

        this.countdownTime = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      }, 1000);
    },
    submitItem() {
      this.$router.go(-1);
    },
    getExamTaskDetail() {
      startExamTask(this.id).then((res) => {
        if (res.code == 200) {
          if (res.data.categoryId == 2) {
            this.ziceTitle = '技能考试';
          } else if (res.data.categoryId == 3) {
            this.ziceTitle = '自测';
          }
          this.examInfo = res.data;
          this.startTimer();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    getQuestionTypeName(type) {
      const types = {
        'determine': '判断题',
        'blank': '填空题',
        'multiple': '选择题',
        'answers': '问答题'
      };
      return types[type] || '';
    },
    selectOption(item, choose, type) {
      if (!item) return;
      if (type == 'mul') {
        if (!Array.isArray(item.answer)) {
          this.$set(item, 'answer', []);
        }
        // 切换选择状态
        const index = item.answer.indexOf(choose);
        if (index === -1) {
          item.answer.push(choose);
        } else {
          item.answer.splice(index, 1);
        }
      }
      else {
        this.$set(item, 'answer', choose);
      }
      // 强制更新当前题目
      this.currentQuestion = { ...this.currentQuestion };
    },
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      } else {
        this.$message.warning('已经是第一题了');
      }
    },
    nextQuestion() {
      if (this.currentQuestion.answer == null || this.currentQuestion.answer == undefined) {
        this.$message.warning('请先答题');
        return;
      }
      if (this.currentIndex < this.listData.length - 1) {
        this.currentIndex++;
      } else {
        this.$message.warning('已经是最后一题了');
      }
    },
    submitExam() {
      // TODO: 实现提交考试逻辑
      this.$confirm('确认提交考试？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        // // // 提交考试的接口调用
        // // const data = {
        // //  ...this.examInfo,
        // //  examTask:{
        // //   ...this.examInfo.examTask,
        // //   temsexamtaskresultList: this.listData.map(v => {
        // //     return {
        // //       ...this.examInfo.examTask.temsexamtaskresultList,
        // //       isAnswers: 1,
        // //       myAnswers: v.answer
        // //     }
        // //   })
        // //  }
        // // }

        let list = this.examInfo.examTask.temsexamtaskresultList;
        this.listData.forEach(item => {
          item.isAnswers = 1;
          item.myAnswers = item.answer;
          if (item.questionType == 'multiple') {
            item.type = '选择题';
            // 选择题
            let b = ['A', 'B', 'C', 'D'];
            let myAnswersResult = item.myAnswers.map(index => b[index]);
            let options = item.options;
            for(let i in options) {
              if (myAnswersResult.indexOf(options[i].label) > -1) {
                options[i].myanswer = true;
              }
              else {
                options[i].myanswer = false;
              }
            }
            item.myAnswers = JSON.stringify(item.myAnswers);
          }
          else if (item.questionType == 'determine') {
            // 判断题 1: 对，0：错
            item.type = '判断题';
            let options = item.options;
            for(let i in options) {
              if (item.myAnswers == options[i].content) {
                options[i].myanswer = false;
              }
              else {
                options[i].myanswer = true;
              }
            }
          }
          else if (item.questionType == 'blank') {
            // 填空题
            item.type = '填空题';
            item.options.push(item.myAnswers);
            item.myAnswers = item.options;
            item.myAnswers = JSON.stringify(item.myAnswers);
          }
          else if (item.questionType == 'answers') {
            // 问答题
            item.type = '问答题';
          }
          item.options = JSON.stringify(item.options);
        })

        delete this.examInfo.examTask;
        const data = {
          submitType: 2,
          ...this.examInfo,
          examId: this.listData[0].examId,
          temsexamtaskresultList: this.listData
        }
        data.id = list[0].taskId;

        // 提交 
        if (list.length == 0) return;
        submitExamTask(list[0].taskId, data).then((res) => {
          if (res.code == 200) {
            this.$message.success('提交成功');
            setTimeout(() => {
              this.$router.push({
                path: "/ExComp/index",
                query: {
                  id: list[0].taskId,
                  type: this.types
                },
              });
            }, 2000);
          } else {
            this.$message.error(res.msg);
          }
        }).catch(() => { });

     })

    }

  },
};
</script>

<style lang="scss" scoped>
.edit {
  box-sizing: border-box;
  height: 100%;
  position: relative;
  padding: 12px;

  .edit-title {
    font-weight: 500;
    font-size: 14px;
    color: #536387;
    line-height: 29px;
    text-align: left;
    font-style: normal;

    .title-1 {
      color: #536387;
      padding-right: 11px;
    }

    .title-2 {
      padding-left: 11px;
      color: #323232;
    }
  }
}

.edit-content {
  display: flex;
  margin-top: 24px;

  .edit-content-left {
    flex: 8;
    background: #fff;
    box-sizing: border-box;
    padding: 24px;
    height: calc(100vh - 200px);

    .edit-content-left-title {
      width: 100%;
      height: 50px;
      font-size: 24px;
      text-align: center;
      border-bottom: 1px solid #f0f2fa;
    }
  }

  .edit-content-right {
    flex: 4;
    margin-left: 20px;
    background: #fff;
    box-sizing: border-box;
    padding: 24px;
    position: relative;

    .edit-content-right-title {
      width: 100%;
      height: 50px;
      font-size: 18px;
      line-height: 50px;
      border-bottom: 1px solid #f0f2fa;
      display: flex;

      div:nth-child(1) {
        flex: 8;
      }

      div:nth-child(2) {
        flex: 4;
      }
    }

    .edit-content-right-content {
      .edit-content-right-item {
        margin-top: 12px;
        width: 100%;
        height: 50px;
        line-height: 50px;
        font-size: 16px;
        position: relative;
        padding-left: 16px;

        &:before {
          content: "";
          width: 4px;
          height: 20px;
          position: absolute;
          left: 0;
          top: 16px;
          background: #2265ee;
        }
      }

      .edit-content-right-item-1 {
        margin-top: 24px;
        display: flex;

        .edit-content-right-item-2 {
          width: 100px;
          height: 40px;
          line-height: 40px;
          text-align: center;
          border: 1px solid #2265ee;
          color: #2265ee;
          margin-right: 10px;
          border-radius: 4px;
          font-size: 14px;
          cursor: pointer;
        }
      }
    }
  }
}

.active {
  background: #2265ee;
  color: #fff !important;
}

.edit-content-right-btn {
  width: 90%;
  position: absolute;
  bottom: 30px;
  display: flex;

  .el-button {
    width: 80%;
    height: 40px;
  }

  .el-button:nth-child(2) {
    background: #2265ee;
    color: #fff;
    border: 1px solid #2265ee;

    &:active {
      opacity: 0.8;
    }
  }
}

.edit-content-left-content {
  width: 100%;
}

.edit-content-left-content-item1 {
  display: flex;
  margin-top: 24px;
  font-size: 24px;
  width: 100%;

  div:nth-child(1) {
    flex: 8;
    text-align: left;
  }

  div:nth-child(2) {
    flex: 4;
    text-align: right;
  }
}

.edit-content-left-content-item2 {
  margin-top: 24px;
  font-size: 18px;

  img {
    width: 260px;
  }
}

.edit-content-left-content-item2-1 {
  display: flex;

  width: 100%;

  // height: 100px;

  border-radius: 4px;

  margin-top: 20px;

  justify-content: space-around;

  align-items: center;

  flex-wrap: wrap; //设置换行

  gap: 10px; //每个元素间隔10px

  div {
    border: 1px solid #f1f4fb;
    display: flex;

    border-radius: 5px;

    justify-content: space-around;

    align-items: center;

    width: calc(50% - 20px); //设置所占宽度50%，再减去20px

    padding: 10px;

    box-sizing: border-box; //设置后宽高不变，不会因为间隔而变小
  }
}
</style>
